<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose"
    :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <div class="adddict">
        <el-form-item prop="dictName" label="字典名称">
          <mt-input v-model="form.dictName"></mt-input>
        </el-form-item>
        <el-form-item v-if="type === 'edit'" label="字典值">
          <mt-input v-model="form.dictCode" :disabled="type === 'edit'"></mt-input>
        </el-form-item>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <mt-button type="submain" @click="handleClose">取消</mt-button>
      <mt-button @click="addNewType">{{ btnName }}</mt-button>
    </span>
  </el-dialog>
</template>

<script>
import { resetObject } from "@/utils/index.js";
export default {
  name: "AddDict",

  props: {},

  data () {
    return {
      form: {
        id: "",
        dictName: "",
        dictCode: "",
        typeCode: ""
      },
      rules: {
        dictName: [{ required: true, message: "请输入字典类型", trigger: "change" }]
      },
      type: "add", // 新建或编辑

      dialogVisible: false
    };
  },

  computed: {
    title () {
      return this.type === "add" ? "新增字典分类" : "修改字典分类";
    },
    btnName () {
      return this.type === "add" ? "新增" : "修改";
    }
  },

  created () {},

  mounted () {},

  methods: {
    /* 外部触发 */
    start (add = true, data) {
      this.type = add ? "add" : "edit";
      if (add) this.form.parentCode = data.dictCode;
      else this._.assign(this.form, data);
      this.dialogVisible = true;
    },

    /* 新增&编辑 */
    async addNewType () {
      if (this.type === "add") {
        const params = {
          dictName: this.form.dictName,
          parentCode: this.form.parentCode
        };
        await this.$request.post(this.API.ADD_DICT_CATALOG, params).then(res => {
          if (res.success) {
            this.$mtMessage({ type: "success", message: "新增成功!" });
            this.DICT.setDictByApi(params.dictCode); // 更新本地字典
            this.$emit("refresh");
            this.handleClose();
          }
        });
      }
      else if (this.type === "edit") {
        const params = {
          id: this.form.id,
          type: 1,
          dictCode: this.form.typeCode,
          dictName: this.form.dictName,
          parentCode: this.form.dictCode
        };
        await this.$request.post(this.API.UPDATE_DICT_CATALOG, params).then(res => {
          if (res.success) {
            this.$mtMessage({ type: "success", message: "修改成功!" });
            // this.DICT.setDictByApi(params.dictCode); // 更新本地字典
            this.$emit("refresh");
            this.handleClose();
          }
        });
      }
    },

    /* 弹窗关闭 */
    handleClose () {
      this.$refs["form"].resetFields();
      this.dialogVisible = false;
    }
  }
};
</script>

<style lang="scss" scoped>
</style>
